package com.dgz.friend.service.user.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dgz.common.core.constants.CacheConstants;
import com.dgz.common.core.constants.Constants;
import com.dgz.common.core.constants.HttpConstants;
import com.dgz.common.core.domain.LoginUser;
import com.dgz.common.core.domain.R;
import com.dgz.common.core.domain.vo.LoginUserVo;
import com.dgz.common.core.enums.ResultCode;
import com.dgz.common.core.enums.UserIdentity;
import com.dgz.common.core.enums.UserStatus;
import com.dgz.common.core.uitls.ThreadLocalUtil;
import com.dgz.common.message.service.AliSmsService;
import com.dgz.common.redis.service.RedisService;
import com.dgz.common.security.exception.ServiceException;
import com.dgz.common.security.service.TokenService;
import com.dgz.friend.domain.user.User;
import com.dgz.friend.domain.user.dto.UserDTO;
import com.dgz.friend.domain.user.dto.UserUpdateDTO;
import com.dgz.friend.domain.user.vo.UserVO;
import com.dgz.friend.manager.UserCacheManager;
import com.dgz.friend.mapper.user.UserMapper;
import com.dgz.friend.service.user.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: DongGuoZhen
 * @Date: 2025/04/24/15:02
 * @Description:
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private AliSmsService aliSmsService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserCacheManager userCacheManager;

    @Value("${sms.code-expiration:5}")
    private Long phoneCodeExpireTime;

    @Value("${sms.send-limit:3}")
    private Long sendLimit;

    @Value("${jwt.secret}")
    private String secret;

    @Value("${sms.is-send:false}")
    private boolean isSend;  // 开关打开为true，关闭为false

    @Value("${file.oss.downloadUrl}")
    private String downloadUrl;

    @Override
    public boolean sendCode(UserDTO userDTO) {
        // 判断手机号是否合法
        if(!checkPhone(userDTO.getPhone())) {
            throw new ServiceException(ResultCode.FAILED_USER_PHOTO);
        }
        // 判断验证码是否过期
        Long expireTime = redisService.getExpire(getPhoneCodeKey(userDTO.getPhone()), TimeUnit.SECONDS);
        if(expireTime != null && (phoneCodeExpireTime * 60 - expireTime) < 60) {
            throw new ServiceException(ResultCode.FAILED_FREQUENT);
        }
        // 判断每天的发送次数50次，第二天0点重置
        // 获取当前用户的验证码请求次数
        Long sendTimes = redisService.getCacheObject(getCodeTimeKey(userDTO.getPhone()), Long.class);
        if(sendTimes != null && sendTimes >= sendLimit) {
            throw new ServiceException(ResultCode.FAILED_TIME_LIMIT);
        }
        // 生成验证码
        String code = isSend ? RandomUtil.randomNumbers(6): Constants.DEFAULT_CODE;
        if(isSend) {
            // 发送验证码
            boolean sendMobileCode = aliSmsService.sendMobileCode(userDTO.getPhone(), code);
            if(!sendMobileCode) {
                throw new ServiceException(ResultCode.FAILED_SEND_CODE);
            }
        }
        // 验证码有效期5分钟
        redisService.setCacheObject(getPhoneCodeKey(userDTO.getPhone()), code, phoneCodeExpireTime, TimeUnit.MINUTES);
        // 记录发送次数+1
        redisService.increment(getCodeTimeKey(userDTO.getPhone()));
        if(sendTimes == null) {  // 当天第一次发送 计算当前时间和第二天0点的时间差 单位秒
            long seconds = ChronoUnit.SECONDS.between(LocalDateTime.now(),
                    LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0));
            redisService.expire(getCodeTimeKey(userDTO.getPhone()),seconds, TimeUnit.SECONDS);
        }
        return true;

    }

    @Override
    public String codeLogin(String phone, String code) {
        checkCode(phone, code);
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone, phone));
        if(user == null) {
            // 注册逻辑
            user = new User();
            user.setPhone(phone);
            user.setStatus(UserStatus.NORMAL.getValue());
            userMapper.insert(user);
        }
        // 生成token
        return tokenService.createToken(user.getUserId(), secret, UserIdentity.ORDINARY.getValue(), user.getNickName(),user.getHeadImage());
    }

    @Override
    public boolean logout(String token) {
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        return tokenService.deleteLoginUser(token, secret);
    }


    @Override
    public R<LoginUserVo> info(String token) {
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        LoginUser loginUser = tokenService.getLoginUser(token, secret);
        if(loginUser == null) {
            return R.fail();
        }
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setNickName(loginUser.getNickName());
        if(StrUtil.isNotEmpty(loginUser.getHeadImage())) {
            loginUserVo.setHeadImage(downloadUrl + loginUser.getHeadImage());
        }
        return R.ok(loginUserVo);
    }

    @Override
    public UserVO detail() {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        if (userId == null) {
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        UserVO userVO = userCacheManager.getUserById(userId);
        if (userVO == null) {
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        if (StrUtil.isNotEmpty(userVO.getHeadImage())) {
            userVO.setHeadImage(downloadUrl + userVO.getHeadImage());
        }
        return userVO;
    }


    @Override
    public int edit(UserUpdateDTO userUpdateDTO) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        if (userId == null) {
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        user.setNickName(userUpdateDTO.getNickName());
        user.setSex(userUpdateDTO.getSex());
        user.setSchoolName(userUpdateDTO.getSchoolName());
        user.setMajorName(userUpdateDTO.getMajorName());
        user.setPhone(userUpdateDTO.getPhone());
        user.setEmail(userUpdateDTO.getEmail());
        user.setWechat(userUpdateDTO.getWechat());
        user.setIntroduce(userUpdateDTO.getIntroduce());
        //更新用户缓存
        userCacheManager.refreshUser(user);
        tokenService.refreshLoginUser(user.getNickName(),user.getHeadImage(),
                ThreadLocalUtil.get(Constants.USER_KEY, String.class));
        return userMapper.updateById(user);
    }

    @Override
    public int updateHeadImage(String headImage) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        if (userId == null) {
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new ServiceException(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        user.setHeadImage(headImage);
        //更新用户缓存
        userCacheManager.refreshUser(user);
        tokenService.refreshLoginUser(user.getNickName(),user.getHeadImage(),
                ThreadLocalUtil.get(Constants.USER_KEY, String.class));
        return userMapper.updateById(user);
    }

    private void checkCode(String phone, String code) {
        String phoneCodeKey = getPhoneCodeKey(phone);
        String phoneCode = redisService.getCacheObject(phoneCodeKey, String.class);
        if(StrUtil.isEmpty(phoneCode)) {
            throw new ServiceException(ResultCode.FAILED_CODE_INVALID);
        }
        if(!phoneCode.equals(code)) {
            throw new ServiceException(ResultCode.FAILED_CODE_ERROR);
        }
        // 验证码验证成功，删除验证码缓存
        redisService.deleteObject(phoneCodeKey);
    }


    public static boolean checkPhone(String phone) {
        Pattern regex = Pattern.compile("^1[2|3|4|5|6|7|8|9][0-9]\\d{8}$");
        Matcher m = regex.matcher(phone);
        return m.matches();
    }

    private String getPhoneCodeKey(String phone) {
        return CacheConstants.PHONE_CODE_KEY + phone;
    }
    private String getCodeTimeKey(String photo) {
        return CacheConstants.CODE_TIME_KEY + photo;
    }
}
